import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
// import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  // timeout: 3000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers.Authorization = `Bearer ${store.getters.token}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const { data, success, message } = response.data
    if (success) {
      return data
    } else {
      Message({
        type: 'error',
        message: message,
        duration: 3 * 1000
      })
      return Promise.reject(new Error(message))
    }
  },
  error => {
    // return error
    console.dir(error)
    if (error.response && error.response.status === 401) {
      if (router.currentRoute.path === '/login') return
      Message({
        type: 'error',
        message: error.response.data.message,
        duration: 3 * 1000
      })
      store.dispatch('user/logoutAction')
      router.replace(`/login?redirect=${router.currentRoute.path}`)
    }

    return Promise.reject(new Error(error))
  })

export default service
